package com.wnhz.work.yz.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.meiqia.core.MQManager;
import com.meiqia.core.bean.MQMessage;
import com.meiqia.core.callback.OnGetMessageListCallback;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.wnhz.work.yz.MainActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.activity.BashRoomListActivity;
import com.wnhz.work.yz.activity.InstallDetailsActivity;
import com.wnhz.work.yz.activity.LoginNewActivity;
import com.wnhz.work.yz.activity.ReceiveAll2Activity;
import com.wnhz.work.yz.activity.SearchActivity;
import com.wnhz.work.yz.activity.YZServiceSelectActivity;
import com.wnhz.work.yz.activity.YanShou2AnActivity;
import com.wnhz.work.yz.activity.YanShouAllActivity;
import com.wnhz.work.yz.activity.YanShouCPDeActivity;
import com.wnhz.work.yz.activity.YanShouDaiActivity;
import com.wnhz.work.yz.activity.YuShouActivity;
import com.wnhz.work.yz.bean.InstallDetailsBean;
import com.wnhz.work.yz.bean.YscpdBean;
import com.wnhz.work.yz.constant.Constants;
import com.wnhz.work.yz.utils.BroadCastReceiverUtil;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * A simple {@link Fragment} subclass.
 * ---优住
 */
public class HomeFragment1 extends Fragment implements View.OnClickListener, BroadCastReceiverUtil.OnReceiveBroadcast {
    private View view;
    private Home1HomePage fragment1;
    private Home1Classify fragment2;
    private Home1Brand fragment3;
    private Home1Order fragment4;

    private List<Fragment> fragmentList;
    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;

    private TextView text1, text2, text3, text4;

    private int textColorNor, textColorCli;
    private View line1, line2, line3, line4;

    private MainActivity activity;
    private RelativeLayout search;
    private TextView tv_number;
    private ImageView yugou, mu;

    BroadcastReceiver broadcastReceiver;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home_fragment1, container, false);
        activity = (MainActivity) getActivity();
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);




        isHaveYuShou();
        initData();
        initView();
        broadcastReceiver = BroadCastReceiverUtil.registerBroadcastReceiver(getContext(), new String[]{ Constants.LOGO_SUCCESS}, HomeFragment1.this);
        return view;
    }

    private void initVisiable() {
        Map<String, Object> map = new HashMap<>();
        if(MyApplication.getInstance().getUserBean() != null){
            map.put("token", MyApplication.getInstance().getUserBean().getToken());
        }
        XUtil.Post(Url.ANZHUANGXIANYIN, map, new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("首页显隐==", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if("1".equals(jsonObject.optString("result"))){
                        text4.setVisibility(View.GONE);
                        line4.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });

    }

    private void initData() {
        textColorNor = getResources().getColor(R.color.text_two);
        textColorCli = getResources().getColor(R.color.main_color);
    }

    @Override
    public void onResume() {
        MQManager.getInstance(activity).getUnreadMessages(new OnGetMessageListCallback() {
            @Override
            public void onSuccess(List<MQMessage> messageList) {
                if (messageList.size() > 0) {
                    tv_number.setText(messageList.size() + "");
                    tv_number.setVisibility(View.VISIBLE);
                } else {
                    tv_number.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(int code, String message) {
            }
        });
        // isHaveYuShou();
        super.onResume();
    }

    private String hasMuStatus;

    public void isHaveYuShou() {
        Map<String, Object> map = new HashMap<>();
        activity.showDialog();
        XUtil.Post(Url.BOOKING_INDEXBOOKINGSTATUS, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                activity.showDialog();
                Log.i("----mmmm", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("status");
                    hasMuStatus = res;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                activity.closeDialog();
//                //TODO 暂时隐藏：：：：：
//                hasMuStatus = "0";
                if ("1".equals(hasMuStatus)) {
                    liShow();
                }
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                activity.closeDialog();
            }
        });
    }

    private void liShow() {
        TranslateAnimation ta = new TranslateAnimation(0, -30f, 0, 0);
        ta.setFillAfter(true);
        mu.startAnimation(ta);
        isShow = false;
        ta.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mu.setVisibility(View.VISIBLE);
                yugou.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void initView() {
        initVisiable();
        view.findViewById(R.id.ll_search).setOnClickListener(this);
        tv_number = (TextView) view.findViewById(R.id.tv_number);
        view.findViewById(R.id.et_search).setOnClickListener(this);
        view.findViewById(R.id.rl_news).setOnClickListener(this);
        view.findViewById(R.id.rl_top).setOnClickListener(this);
        text1 = (TextView) view.findViewById(R.id.tv_homePage);
        text2 = (TextView) view.findViewById(R.id.tv_classify);
        text3 = (TextView) view.findViewById(R.id.tv_brand);
        text4 = (TextView) view.findViewById(R.id.tv_order);


        line1 = view.findViewById(R.id.line1);
        line2 = view.findViewById(R.id.line2);
        line3 = view.findViewById(R.id.line3);
        line4 = view.findViewById(R.id.line4);

        text1.setOnClickListener(this);
        text2.setOnClickListener(this);
        text3.setOnClickListener(this);
        text4.setOnClickListener(this);

        fragmentList = new ArrayList<>();
        fragment1 = new Home1HomePage();
        fragment2 = new Home1Classify();
        fragment3 = new Home1Brand();
        fragment4 = new Home1Order();

        fragmentList.add(fragment1);
        fragmentList.add(fragment2);
        fragmentList.add(fragment3);
        fragmentList.add(fragment4);

        fragmentManager = getFragmentManager();
        transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.fl_home1, fragment1);
        transaction.add(R.id.fl_home1, fragment2);
        transaction.add(R.id.fl_home1, fragment3);
        transaction.add(R.id.fl_home1, fragment4);

        transaction.hide(fragment2);
        transaction.hide(fragment3);
        transaction.hide(fragment4);
        transaction.commit();
        mu = (ImageView) view.findViewById(R.id.img_mu);
        mu.setOnClickListener(this);

        yugou = (ImageView) view.findViewById(R.id.yugou);
        yugou.setOnClickListener(this);

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        MQManager.getInstance(activity).getUnreadMessages(new OnGetMessageListCallback() {
            @Override
            public void onSuccess(List<MQMessage> messageList) {
                if (messageList.size() > 0) {
                    tv_number.setText(messageList.size() + "");
                    tv_number.setVisibility(View.VISIBLE);
                } else {
                    tv_number.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(int code, String message) {
            }
        });
        fragment1.onHiddenChanged(hidden);
        super.onHiddenChanged(hidden);
    }

    private void hideFragment(int index) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        for (int i = 0; i < fragmentList.size(); i++) {
            if (i == index) {
                transaction.show(fragmentList.get(i));
            } else {
                transaction.hide(fragmentList.get(i));
            }
        }
        transaction.commit();
    }


    @Override
    public void onClick(View view) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        Intent intent;
        switch (view.getId()) {
            //搜索
            case R.id.et_search:
                activity.closrKeyboard();
                intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);

//                activity.MyToast("搜索");
                break;

            //消息
            case R.id.rl_news:
//                intent = new Intent(getActivity(), ReceptionEvaluateActivity.class);
//                startActivity(intent);
                if (MyApplication.getInstance().getUserBean() == null) {
                    Toast.makeText(getContext(), "请登录", Toast.LENGTH_SHORT).show();
                    Intent intent2 = new Intent(getContext(), LoginNewActivity.class);
                    startActivity(intent2);
                    return;
                }
                intent = new Intent(getActivity(), YZServiceSelectActivity.class);
                startActivity(intent);
                break;

            //首页
            case R.id.tv_homePage:
                hideFragment(0);
                transaction.show(fragmentList.get(0)).commit();
                text1.setTextColor(textColorCli);
                text2.setTextColor(textColorNor);
                text3.setTextColor(textColorNor);
                text4.setTextColor(textColorNor);

                line1.setVisibility(View.VISIBLE);
                line2.setVisibility(View.INVISIBLE);
                line3.setVisibility(View.INVISIBLE);
                line4.setVisibility(View.GONE);
                if ("1".equals(hasMuStatus))
                    liShow();
//                mu.setVisibility(View.VISIBLE);
                break;

            //分类
            case R.id.tv_classify:
                hideFragment(1);
                transaction.show(fragmentList.get(1)).commit();
                text1.setTextColor(textColorNor);
                text2.setTextColor(textColorCli);
                text3.setTextColor(textColorNor);
                text4.setTextColor(textColorNor);

                line1.setVisibility(View.INVISIBLE);
                line2.setVisibility(View.VISIBLE);
                line3.setVisibility(View.INVISIBLE);
                line4.setVisibility(View.GONE);
                mu.setVisibility(View.GONE);
                yugou.setVisibility(View.GONE);
                isShow = false;
                noShow();
                break;

            //品牌
            case R.id.tv_brand:
                hideFragment(2);
                transaction.show(fragmentList.get(2)).commit();
                text1.setTextColor(textColorNor);
                text2.setTextColor(textColorNor);
                text3.setTextColor(textColorCli);
                text4.setTextColor(textColorNor);

                line1.setVisibility(View.INVISIBLE);
                line2.setVisibility(View.INVISIBLE);
                line3.setVisibility(View.VISIBLE);
                line4.setVisibility(View.GONE);
                mu.setVisibility(View.GONE);
                isShow = false;
                noShow();
                break;
            //
            case R.id.tv_order:
                hideFragment(3);
                transaction.show(fragmentList.get(3)).commit();
                text1.setTextColor(textColorNor);
                text2.setTextColor(textColorNor);
                text3.setTextColor(textColorNor);
                text4.setTextColor(textColorCli);

                line1.setVisibility(View.INVISIBLE);
                line2.setVisibility(View.INVISIBLE);
                line3.setVisibility(View.INVISIBLE);
                line4.setVisibility(View.VISIBLE);
                fragment4.onResume();
                mu.setVisibility(View.GONE);
                isShow = false;
                noShow();
                break;

            case R.id.yugou: {
                startActivity(new Intent(activity, YuShouActivity.class));
                TranslateAnimation ta = new TranslateAnimation(0, -30f, 0, 0);
                ta.setDuration(600);
                ta.setFillAfter(true);
                mu.startAnimation(ta);
                ta.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        yugou.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }
            break;
            case R.id.img_mu:
                isShow = !isShow;
                if (isShow) {
                    TranslateAnimation ta = new TranslateAnimation(-30f, 0, 0, 0);
                    ta.setDuration(600);
                    ta.setFillAfter(true);
                    mu.startAnimation(ta);
                    ta.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            yugou.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                } else {
                    noShow();
                }

                break;
            case R.id.ll_search:
                startActivityForResult(new Intent(activity, CaptureActivity.class), 0);
                break;
            default:
                break;
        }
    }


    public void noShow() {
        TranslateAnimation ta = new TranslateAnimation(0, -30f, 0, 0);
        ta.setDuration(600);
        ta.setFillAfter(true);
        mu.startAnimation(ta);
        ta.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                yugou.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private boolean isShow = false;

    //
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0)
            if (resultCode == activity.RESULT_OK) {
                //处理扫描结果（在界面上显示）
                if (null != data) {
                    Bundle bundle = data.getExtras();
                    if (bundle == null) {
                        return;
                    }
                    if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                        String erwei = bundle.getString(CodeUtils.RESULT_STRING);
                        //  ((TextView) view.findViewById(R.id.text888)).setText("" + erwei);
                        Log.e("===", "===" + erwei);
                        //   Toast.makeText(activity, "" + erwei, Toast.LENGTH_LONG).show();
                        //   if (erwei.contains("=")) {
                        if (MyApplication.getInstance().getUserBean() == null) {
                            activity.MyToast("请先登录");
                            return;
                        }
//                        String one = erwei.substring(0, erwei.lastIndexOf("="));
//                        String two = erwei.substring(erwei.lastIndexOf("=") + 1, erwei.length());
                        // onerweima(one, two);
                        twoweima("", erwei);
//                        } else {
//                            activity.MyToast("请扫描本产品二维码！");
//                        }
                    } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                        Toast.makeText(activity, "解析二维码失败", Toast.LENGTH_LONG).show();
                    }
                }
            }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void twoweima(String one, String two) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("order_no", two);
        activity.showDialog();
        Set keys = map.keySet();
        String b = "";
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, "" + value + "\n");
                b += key + "--";
                b += value + ";";
            }
        }
        ((TextView) view.findViewById(R.id.text888)).setText("" + b);

        XUtil.Post(Url.DECORATE_QRCODEGETDECORATE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    String type = jsonObject.optString("type");
                    Log.e("----erererer", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        activity.hideFragment(3);
                        if ("2".equals(type)) {
                            startActivity(new Intent(activity, YanShouAllActivity.class));
                            startActivity(new Intent(activity, YanShouDaiActivity.class));
                            YscpdBean bean1 = gson.fromJson(result, YscpdBean.class);
                            startActivity(new Intent(activity, YanShouCPDeActivity.class)
                                    .putExtra("bean", bean1)
                                    .putExtra("name", bean1.getPackage_name())
                                    .putExtra("position", 0 + "")
                                    .putExtra("house", bean1.getRoom_number() + "")
                                    .putExtra("score", bean1.getScore())
                                    .putExtra("company", bean1.getCompany())
                            );
                        } else if ("1".equals(type)) {
                            InstallDetailsBean bean = gson.fromJson(result, InstallDetailsBean.class);
                            InstallDetailsBean.InfoEntity info2 = bean.getInfo();
                            startActivity(new Intent(activity, ReceiveAll2Activity.class));
                            startActivity(new Intent(activity, YanShou2AnActivity.class));
                            if ("5".equals(info2.getStatus())) {
                                startActivity(new Intent(activity, InstallDetailsActivity.class).putExtra("info2", info2).putExtra("budget_id", info2.getId()).putExtra("type", "" + 1));
                            } else {
                                startActivity(new Intent(activity, InstallDetailsActivity.class).putExtra("info2", info2).putExtra("budget_id", info2.getId()).putExtra("type", "" + 0));
                            }

                        }
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        activity.MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                activity.closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                activity.closeDialog();
                ex.printStackTrace();
            }
        });

    }

    private void onerweima(String one, String two) {
        Map<String, Object> map = new HashMap<>();

        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("order_no", two);
        activity.showDialog();
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----erweima" + key, "" + value + "\n");
            }
        }
        XUtil.Post(Url.DECORATE_QRCODEDECORATEORDERDETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        activity.MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                activity.closeDialog();

                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                activity.closeDialog();
                ex.printStackTrace();
            }
        });
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Constants.LOGO_SUCCESS)) {
            isHaveYuShou();
        }

    }
}
